<?php


namespace app\admin\controller;

require_once __DIR__ . '/../../../vendor/autoload.php';

use app\BaseController;
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Request;

class Upload extends BaseController {


	static function upload() {
		$file = $_FILES['file'];
		$harmtype = array('asp', 'php', 'jsp', 'js', 'css', 'php3', 'php4', 'php5', 'ashx', 'aspx', 'exe', 'cgi');
		$type = $file['type'];
		if (empty($file)) {
			exit (json_encode(array('code' => 0, 'msg' => '没有上传内容')));
		}
		$ext = strtolower($type);
		if (in_array($ext, $harmtype)) {//防止注入
			exit (json_encode(array('code' => 0, 'msg' => '上传文件类型错误')));
		}
		$result = array();
		$path = "{$type}s/" . date('Y/m/');
		self::mkdirs(  $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR . $path);
		$filename = self::file_random_name($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $path, $ext);
		$result['path'] = $path . $filename;
		$save_path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $result['path'];
		if (!self::file_move($file->getPathname(), $save_path)) {
			exit (json_encode(array('code' => -1, 'msg' => '保存上传文件失败')));
		}
		$image_src = self::oss($filename, $save_path);
		dump($image_src);
	}

	static function mkdirs($path) {
		if (!is_dir($path)) {
			self::mkdirs(dirname($path));
			mkdir($path);
		}
		return is_dir($path);
	}

	static function file_random_name($dir, $ext) {
		do {
			$filename = self::random(30) . '.' . $ext;
		} while (file_exists($dir . $filename));

		return $filename;
	}

	static function random($length, $numeric = FALSE) {
		$seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
		$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
		if ($numeric) {
			$hash = '';
		} else {
			$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
			$length--;
		}
		$max = strlen($seed) - 1;
		for ($i = 0; $i < $length; $i++) {
			$hash .= $seed{mt_rand(0, $max)};
		}
		return $hash;
	}

	static function file_move($filename, $dest) {
		self::mkdirs(dirname($dest));
		if (is_uploaded_file($filename)) {
			move_uploaded_file($filename, $dest);
		} else {
			rename($filename, $dest);
		}
		return is_file($dest);
	}

	static function oss($a, $b) {
		$accessKeyId = "LTAI4G6uKcPKgjgwUYNZGWzJ";
		$accessKeySecret = "lkdbbtxVWqVyDNcPPcyC5M9PW11eiy
";
		$endpoint = "oss-cn-beijing.aliyuncs.com";
		$bucket = "withthemind-zsff";
		$object = $a;
		$filePath = $b;
		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$ossClient->uploadFile($bucket, $object, $filePath);
			$ossClient = (array)$ossClient;
			$image_src = array_values($ossClient)[4];
			return $image_src;
		} catch (OssException $e) {
			printf(__FUNCTION__ . ": FAILED\n");
			printf($e->getMessage() . "\n");
			return [];
		}
	}

}